import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:dio/dio.dart';
import '../../http/Api.dart';
import '../../http/HttpUtil.dart';
import '../../entity/BankEntity.dart';
import '../../util/AppSaveInfoUtil.dart';
import '../../base/Constant.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_easyrefresh/material_footer.dart';

class BankPageLsit extends StatefulWidget {
  BankPageLsit({Key key}) : super(key: key);

  @override
  _BankPageLsitState createState() => _BankPageLsitState();
}

class _BankPageLsitState extends State<BankPageLsit> {
  double kMargin5 = ScreenUtil().setWidth(5);
  double kMargin20 = ScreenUtil().setWidth(20);

  List<BankEntity> articles = new List();
  int page = 1;
  String token = "";
 EasyRefreshController _controller = new EasyRefreshController();

  @override
  void deactivate() {
    var bool = ModalRoute.of(context).isCurrent;

    if (bool) {
      print("页面即将显示");
      getString(TOKEN).then((value) {
        token = value;
        loadList();
      });
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      loadList();
    });
  }

  loadList() async {
    FormData formData = new FormData.fromMap({
      "token": token,
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_BANK_LIST, data: formData);
    Map userMap = json.decode(response.data);
    print(userMap);
    if (userMap['code'] == 1 && mounted) {
      articles.clear();
      // _easyRefreshKey.currentState.callRefreshFinish();
      _controller.finishRefresh();
      (userMap['data']['list'] as List).forEach((v) {
        articles.add(new BankEntity.fromJson(v));
      });
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          "选择银行",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.5,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
      ),
      body: new Container(
        color: divideColor,
        child: new EasyRefresh(
         controller: _controller,
          header: MaterialHeader(),
          footer: MaterialFooter(),
          child: ListView.separated(
              itemBuilder: _buildListItem,
              separatorBuilder: (BuildContext context, int index) {
                return Container(
                  color: divideColor,
                  height: 1,
                );
              },
              itemCount: articles.length),
          onRefresh: () async {
            page = 1;
            loadList();
          },
          onLoad: () async {
            page++;
            loadList();
          },
        ),
      ),
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    return new GestureDetector(
        onTap: () {
          // 当前选中
          BankEntity model = articles[index];
          // saveString(BANK_ID, model.bank_id);
          // saveString(BANK_NAME, model.bank_name);
          Navigator.of(context).pop(model);
        },
        child: Container(
            margin: EdgeInsets.fromLTRB(
                kMargin5, ScreenUtil().setHeight(15), kMargin5, 0),
            color: Colors.white,
            child: Column(
              children: <Widget>[
                Row(children: <Widget>[
                  _leftImage(index),
                  Expanded(
                    child: _rightColumn(index),
                  ),
                  _pd(
                      Icon(
                        Icons.arrow_forward_ios,
                        color: Colors.black87,
                        size: 20,
                      ),
                      l: kMargin20,
                      t: kMargin20 * 3,
                      r: 5,
                      b: 0)
                ], crossAxisAlignment: CrossAxisAlignment.start),
                Divider(
                  height: 1,
                )
              ],
            )));
  }

  Widget _pd(Widget w, {double l, double t, double r, double b}) {
    //边距
    return Padding(
        padding: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(l) ?? 0,
            ScreenUtil().setHeight(t) ?? 0,
            ScreenUtil().setWidth(r) ?? 0,
            ScreenUtil().setHeight(b) ?? 0),
        child: w);
  }

  Widget _leftImage(int index) {
    //左图
    var image = Image.network(
      Api.ImgBaseUrl + articles[index].icon,
      width: ScreenUtil().setHeight(100),
      height: ScreenUtil().setHeight(100),
      fit: BoxFit.cover,
    );
    // var image = new Image(
    //     image: AssetImage('images/icon_setup_bankcard.png'),
    //     width: ScreenUtil().setHeight(100),
    //     height: ScreenUtil().setHeight(100),
    //     fit: BoxFit.fill);
    return _pd(image, l: kMargin20, t: 0, r: 5, b: kMargin20);
  }

  Widget _rightColumn(int index) {
    var name = RichText(
        text: TextSpan(style: TextStyle(color: Colors.black), children: [
      TextSpan(
          text: articles[index].bank_name, style: TextStyle(fontSize: 14.0)),
    ]));

    return _pd(name, l: kMargin20, t: kMargin20 * 3, r: 5, b: 0);
  }
}
